package cn.tedu.baking.service.impl;

import cn.tedu.baking.mapper.CommentMapper;
import cn.tedu.baking.mapper.ContentMapper;
import cn.tedu.baking.pojo.dto.ContentDTO;
import cn.tedu.baking.pojo.entity.Content;
import cn.tedu.baking.pojo.vo.*;
import cn.tedu.baking.service.IContentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.List;

@Service
public class ContentService implements IContentService {
    @Autowired
    ContentMapper mapper;
    @Override
    public void addNew(ContentDTO contentDTO) {
        Content content = new Content();
        BeanUtils.copyProperties(contentDTO,content);

        //通过有没有id判断是发布还是修改
        if (content.getId()==null){//发布
            content.setCreateTime(new Date());
            mapper.insert(content);
        }else{//修改
            content.setUpdateTime(new Date());
            mapper.update(content);
        }

    }

    @Override
    public List<ContentManagementVO> listForManagement(Long type, Long userId) {
        return mapper.selectForManagementByTypeAndUserId(type,userId);
    }
    @Value("${file-path}")
    private String dirPath;
    @Autowired
    CommentMapper commentMapper;
    @Override
    public void deleteById(Long id) {
        //删除相关评论
        commentMapper.deleteByContentId(id);

        ContentUpdateVO updateVO = mapper.selectForUpdateById(id);
        if (updateVO.getType()==2){//视频
            new File(dirPath+updateVO.getVideoUrl()).delete();
        }else{//图片
            new File(dirPath+updateVO.getImgUrl()).delete();
        }


        mapper.deleteById(id);
    }

    @Override
    public ContentUpdateVO updateById(Long id) {
        return mapper.selectForUpdateById(id);
    }

    @Override
    public List<ContentIndexVO> listForIndex(Long type, Long categoryId) {
        return mapper.selectForIndex(type,categoryId);
    }

    @Override
    public ContentDetailVO detailById(Long id) {
        //让浏览量+1
        mapper.updateViewCountById(id);

        return mapper.selectForDetailById(id);
    }

    @Override
    public List<ContentSimpleVO> otherListByUserId(Long id) {
        return mapper.selectForOtherByUserId(id);
    }

    @Override
    public List<ContentSimpleVO> hotList() {
        return mapper.selectForHot();
    }

    @Override
    public List<ContentIndexVO> listByType(Long type) {
        return mapper.selectByType(type);
    }

    @Override
    public List<ContentIndexVO> searchByWd(String wd) {
        return mapper.selectByWd(wd);
    }

    @Override
    public List<ContentAdminVO> listForAdmin() {
        return mapper.selectForAdmin();
    }

}
